package router

import (
	"gin-lite/internal/api/admin"
	"gin-lite/internal/pkg/core"
	"gin-lite/internal/pkg/env"
	"gin-lite/internal/pkg/timeutil"
	"gin-lite/internal/repository/mysql"
	"github.com/pkg/errors"
	"github.com/redis/go-redis/v9"
	"go.uber.org/zap"
)

func NewHTTPMux(logger *zap.Logger, db *mysql.Repo, redis *redis.Client) (core.Mux, error) {
	if logger == nil {
		return nil, errors.New("logger required")
	}

	if db == nil {
		return nil, errors.New("db required")
	}

	if redis == nil {
		return nil, errors.New("redis required")
	}

	mux, err := core.New(logger, core.WithEnableCors(), core.WithEnablePProf())
	if err != nil {
		panic(err)
	}

	system := mux.Group("/system")
	{
		// 健康检查
		system.GET("/health", func(ctx core.Context) {
			resp := &struct {
				Time        string `json:"time"`
				Environment string `json:"environment"`
				Host        string `json:"host"`
				Status      string `json:"status"`
			}{
				Time:        timeutil.CSTLayoutString(),
				Environment: env.Active().Value(),
				Host:        ctx.Host(),
				Status:      "ok",
			}
			ctx.Payload(resp)
		})
	}

	// 示例 CURD，操作 mysql admin 表
	adminHandler := admin.New(logger, db, redis)
	adminRouter := mux.Group("/api")
	{
		// 创建管理员
		adminRouter.POST("/admin/create", adminHandler.Create())
		// 管理员列表
		adminRouter.GET("/admin/list", adminHandler.List())
		// 单个管理员
		adminRouter.GET("/admin.first", adminHandler.First())
		// 删除管理员
		adminRouter.DELETE("/admin/:id", adminHandler.Delete())
	}

	return mux, nil
}
